import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from 'antd';
import AntdFormItem from '@/components/AntdFormItem';
import AntdForm from '@/components/AntdForm';
import StandardTable from '@/components/StandardTable';
import AdSelect from '@/components/AdSelect';
import AntdInput from '@/components/AntdInput';
import { allDictList } from '@/utils/constans';
import { renderTableAdSelect, codes, allDispatchType, getBillTaxList } from './utils';
import { queryDict, formatPrice } from '@/utils/common';
import prompt from '@/components/Prompt';
import styles from './Bill.less';
@connect(({ vehicle, component, loading }) => ({
  billTaxList: vehicle.billTaxList,
  dictObject: component.dictObject,
  loading: loading.effects['vehicle/selectBillTax'],
}))
@Form.create()
export default class BillTax extends Component {
  constructor(props) {
    super(props);
    const {
      form: { getFieldDecorator },
    } = props;
    this.state = {
      billTaxList: [],
      detailId: '',
      preData: {},
    };
    this.commonParams = {
      getFieldDecorator,
    };
  }
  componentWillMount() {
    const allDict = [allDictList.taxRate, allDictList.costSubjects];
    queryDict({ props: this.props, allDict });
  }
  componentDidMount() {
    const { dispatch, detailId, onRef } = this.props;
    onRef && onRef(this);
    if (!detailId) return;
    this.setState({
      detailId,
    });
    getBillTaxList(dispatch, detailId);
  }

  componentWillReceiveProps(nextProps) {
    const { detailId } = nextProps;
    if (this.props.detailId !== detailId) {
      if (detailId) {
        this.setState({
          detailId,
        });
        getBillTaxList(this.props.dispatch, detailId);
      }
    }
  }

  getInfoData = () => {
    const { billTaxList } = this.props;
    const { detailId } = this.state;
    let newData = [];
    if (billTaxList[detailId]) {
      const data = billTaxList[detailId].list;
      newData = data.map(item => ({ ...item }));
    }
    return newData;
  };

  getRowByKey(id, newData) {
    const data = this.getInfoData();
    return (newData || data).filter(item => item.id === id)[0];
  }

  handleFieldChange(value, fieldName, id) {
    const { detailId } = this.state;
    const { dispatch, showTipsFun, realPayable, form } = this.props;
    showTipsFun(true);
    let newData = this.getInfoData();
    const target = this.getRowByKey(id, newData);
    if (target) {
      target[fieldName] = value;
    }

    let utils = {
      calcTax: (itax, icontainTax) => {
        if (itax) target.tax = itax;
        target.containTax = icontainTax;
        this.setState(
          {
            preData: target,
          },
          () => {
            if (itax) form.setFieldsValue({ [`tax-${target.id}`]: itax });
            form.setFieldsValue({ [`containTax-${target.id}`]: icontainTax });
          }
        );
      }
    }
    /*不含税额： unContainTax ； 税率： taxRate ； 税额：tax ; 含税额: containTax
      * 1. 税额 = 不含税额X税率
      * 2. 含税额 = 不含税额 + 税额
      * 3、含税额合计 = 实付金额 (保存提交时校验)
      * 4、税率为0时：含税额=不含税额
    */
    if (fieldName === 'unContainTax') {
      const itax = formatPrice((Number(value) * target.taxRate) / 100);
      const icontainTax = formatPrice(Number(value) + Number(itax));
      utils.calcTax(itax, icontainTax)
    };
    if (fieldName === 'tax') {
      // const itax = formatPrice((Number(value) * target.taxRate) / 100);
      const icontainTax = formatPrice(Number(value) + Number(target.unContainTax));
      utils.calcTax('', icontainTax)
    };

    if (fieldName === 'taxRate') {
      const itax = formatPrice(Number(value) * Number(target.unContainTax) / 100);
      const icontainTax = formatPrice(Number(target.unContainTax) + Number(itax));
      utils.calcTax(itax, icontainTax)
    }
    newData = newData.filter((v, i) => i !== newData.length - 1);
    newData.push({
      id: '0',
      reasons: '',
      type: '合计',
      unContainTax: this.allCount(newData, 'unContainTax'),
      taxRate: '',
      tax: this.allCount(newData, 'tax'),
      containTax: this.allCount(newData, 'containTax'),
    });
    // console.log('newData===', newData)
    this.saveAllValue({ billTaxList: { [detailId]: { list: newData } } });
  }

  allCount = (data, fieldName) => {
    const arr = data.map(v => v[fieldName]);
    return arr.reduce((total, currentValue) => {
      return total + Number(currentValue);
    }, 0);
  };

  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'vehicle/billTaxValue',
      payload: payload || {},
    });
  };

  columns = [
    {
      title: '摘要',
      dataIndex: 'reasons',
      width: 200,
      render: (text, record) => {
        const { dictObject, onlyRead, disabled } = this.props;
        if (!onlyRead && record.id !== '0') {
          return (
            <AntdFormItem
              label=" "
              code={`reasons-${record.id}`}
              initialValue={text}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AntdInput
                disabled={disabled}
                onChange={value => this.handleFieldChange(value, 'reasons', record.id)}
              />
            </AntdFormItem>
          );
        }
        return <span>{text}</span>;
      },
    },
    {
      title: '科目名称',
      dataIndex: 'type',
      width: 150,
      render: (text, record) => {
        const { dictObject, onlyRead, disabled } = this.props;
        if (!onlyRead && record.id !== '0') {
          return (
            <AntdFormItem
              label=" "
              code={`type-${record.id}`}
              initialValue={text}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AdSelect
                disabled={disabled}
                isExist={true}
                data={dictObject[allDictList.costSubjects]}
                payload={{ code: allDictList.costSubjects }}
                onChange={value => this.handleFieldChange(value, 'type', record.id)}
              />
            </AntdFormItem>
          );
        }
        return renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.costSubjects,
        });
      },
    },
    {
      title: '不含税额',
      dataIndex: 'unContainTax',
      width: 150,
      render: (text, record) => {
        const { dictObject, onlyRead, disabled } = this.props;
        if (!onlyRead && record.id !== '0') {
          return (
            <AntdFormItem
              label=" "
              code={`unContainTax-${record.id}`}
              initialValue={formatPrice(text)}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AntdInput disabled={disabled} onChange={value => this.handleFieldChange(value, 'unContainTax', record.id)} />
            </AntdFormItem>
          );
        }
        return <span>{formatPrice(text)}</span>;
      },
    },
    {
      title: '税率',
      dataIndex: 'taxRate',
      width: 150,
      render: (text, record) => {
        const { dictObject, onlyRead, disabled } = this.props;
        if (!onlyRead && record.id !== '0') {
          return (
            <AntdFormItem
              label=" "
              code={`taxRate-${record.id}`}
              initialValue={text}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AdSelect
                disabled={disabled}
                isExist={true}
                data={dictObject[allDictList.taxRate]}
                payload={{ code: allDictList.taxRate }}
                onChange={value => this.handleFieldChange(value, 'taxRate', record.id)}
              />
            </AntdFormItem>
          );
        }
        return renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.taxRate,
        });
      },
    },
    {
      title: '税额',
      dataIndex: 'tax',
      width: 150,
      render: (text, record) => {
        const { dictObject, onlyRead, disabled } = this.props;
        if (!onlyRead && record.id !== '0') {
          return (
            <AntdFormItem
              label=" "
              code={`tax-${record.id}`}
              initialValue={formatPrice(text)}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AntdInput onChange={value => this.handleFieldChange(value, 'tax', record.id)} />
            </AntdFormItem>
          );
        }
        return <span>{formatPrice(text)}</span>;
      },
    },
    {
      title: '含税额',
      dataIndex: 'containTax',
      render: (text, record) => {
        const { dictObject, onlyRead, disabled } = this.props;
        if (!onlyRead && record.id !== '0') {
          return (
            <AntdFormItem
              label=" "
              code={`containTax-${record.id}`}
              initialValue={formatPrice(text)}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AntdInput
                disabled={true}
              // onChange={value => this.handleFieldChange(value, 'containTax', record.id)}
              />
            </AntdFormItem>
          );
        }
        return <span>{formatPrice(text)}</span>;
      },
    },
  ];

  render() {
    const { billTaxList, loading } = this.props;
    const { detailId } = this.state;
    return (
      <Fragment>
        <div className={styles.customPartsOfferInfo}>
          <AntdForm>
            <StandardTable
              disabledRowSelected={true}
              loading={loading}
              data={billTaxList[detailId] || {}}
              columns={this.columns}
              scrollX={800}
              pagination={false}
              scrollY={200}
              canInput={true}
              className="table_info_total"
            />
          </AntdForm>
        </div>
      </Fragment>
    );
  }
}
